//
//  StoreManager.m
//  iFoundIt
//
//  Created by Navid Shariat on 20/05/10.
//  Copyright 2010 QUT. All rights reserved.
//

#import "StoreManager.h"
#import "StorePersistentManager.h"
#import "Store.h"

@implementation StoreManager
@synthesize stores, managedObjectContext;
@synthesize locationManager;

-(void) dealloc{
	[stores dealloc];
	[managedObjectContext dealloc];
	[super dealloc];
}

- (NSMutableArray *) getStores{
	NSFetchRequest *request = [[NSFetchRequest alloc] init];	
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Store" inManagedObjectContext:managedObjectContext];	
	[request setEntity:entity];
	NSError *error;
	NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];	
	if (mutableFetchResults == nil) {
		NSLog(@"no store fetched");
	}	
	[self setStores:mutableFetchResults];	
	[mutableFetchResults release];	
	[request release];	
	return [self stores];
}
- (NSMutableArray *) findStores: (Address *) fromAddress : (int) radius{
	return NULL;
}
- (void) populateWithTestData{

	CLLocation *location = [locationManager location];
	if (!location) {		
        location= [[CLLocation alloc] init];		
    }
	
	if (![self managedObjectContext])
		managedObjectContext= [[NSManagedObjectContext alloc] init];
	Store  *store = (Store *)[NSEntityDescription insertNewObjectForEntityForName:@"Store" inManagedObjectContext:managedObjectContext];
	CLLocationCoordinate2D coordinate = [location coordinate];
	[store setName:@"Navid store"];
	[store setSeachKeywords:@"convinient,milk,cream,ice cream"];

	Store  *store2 = (Store *)[NSEntityDescription insertNewObjectForEntityForName:@"Store" inManagedObjectContext:managedObjectContext];
	[store2 setLatitude:1];
	[store2 setLongtitude:1];
	[store2 setName:@"Olivia store"];
	[store2 setSeachKeywords:@"Bike,car	"];
	
	NSError *error;	
	if (![managedObjectContext save:&error]) {
		NSLog(@"error while saving the object,nononono!");
	}
}


- (CLLocationManager *)locationManager {
    if (locationManager != nil) {		
        return locationManager;		
    }
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;	
    locationManager.delegate = self;
    return locationManager;
}

- (NSManagedObjectContext *)managedObjectContext {
    if (managedObjectContext == nil)
		managedObjectContext = [[NSManagedObjectContext alloc] init];
    return managedObjectContext;
}

@end
